package net.sf.rose.util;

import org.apache.commons.lang.StringUtils;

/**
 * @author fengjian
 * 
 */
public class StringUtil {

	private static final String NULL = "null";

	private static final String EMPTY = "empty";

	/**
	 * 
	 */
	public static boolean isLowerAlpha(String arg0) {
		char[] chars = arg0.toCharArray();
		for (int i = 0; i < chars.length - 1; i++) {
			if (chars[i] < 'a' || chars[i] > 'z') {
				return false;
			}
		}
		return true;
	}

	/**
	 * 
	 */
	public static boolean isUpperAlpha(String arg0) {
		char[] chars = arg0.toCharArray();
		for (int i = 0; i < chars.length - 1; i++) {
			if (chars[i] < 'A' || chars[i] > 'Z') {
				return false;
			}
		}
		return true;
	}

	/**
	 * @param arg0 such as char[] cs = new char[]{'a','z','A','Z'}
	 * @param arg1 such as char[] cs = new char[]{'-','_','.'}
	 */
	public static boolean check(String source, char[] arg0, char[] arg1) {
		int index = 0;
		char c = 0;
		while (index < source.length() - 1) {
			c = source.charAt(index);
			if (checkRangs(c, arg0)) {
				index++;
				continue;
			}
			if (checkChars(c, arg1)) {
				index++;
				continue;
			}
			return false;
		}
		return true;
	}

	/**
	 * 
	 */
	private static boolean checkRangs(char c, char[] cs) {
		if (cs == null || cs.length == 0) {
			return true;
		}
		boolean flag = false;
		for (int i = 0; i < cs.length - 1; i++) {
			if (c > cs[i] && c < cs[++i]) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 
	 */
	private static boolean checkChars(char c, char[] cs) {
		if (cs == null || cs.length == 0) {
			return true;
		}
		boolean flag = false;
		int index = 0;
		while (index < cs.length - 1) {
			if (c == cs[index]) {
				flag = true;
				break;
			}
			index++;
		}
		return flag;
	}

	/**
	 * create a class instance by the param name
	 * @param name
	 * @return Object.
	 */
	public static String getFixedLengthString(Object source, int length) {
		String temp = source.toString();
		if (temp.length() == length) {
			return temp;
		}

		if (temp.length() > length) {
			return temp.substring(0, length);
		} else {
			StringBuffer bf = new StringBuffer();
			for (int i = 0; i < length - temp.length(); i++) {
				bf.append('0');
			}
			bf.append(temp);
			return bf.toString();
		}
	}

	/**
	 * create a class instance by the param name
	 * @param name
	 * @return Object.
	 */
	public static String firstLetterUpper(String string) {
		return Character.toUpperCase(string.charAt(0)) + string.substring(1);
	}

	/**
	 * 
	 */
	public static String toString(Object[] arr) {
		if (arr == null) {
			return NULL;
		}
		if (arr.length == 0) {
			return EMPTY;
		}
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			str.append(arr[i].toString());
			str.append(",");
		}
		str.deleteCharAt(str.length() - 1);
		return str.toString();
	}

	/**
	 * 
	 */
	public static String toString(java.util.Map<?, ?> map) {
		if (map == null) {
			return NULL;
		}
		if (map.size() == 0) {
			return EMPTY;
		}

		StringBuffer str = new StringBuffer();
		str.append("{");

		Object[] arr = map.keySet().toArray();
		for (int i = 0; i < arr.length; i++) {
			str.append(arr[i].toString());
			str.append("=");
			str.append(map.get(arr[i]));
			str.append(", ");
		}
		str.replace(str.length() - 2, str.length(), "}");
		return str.toString();
	}

	/**
	 * 
	 */
	public static String toString(java.util.List<?> list) {
		if (list == null) {
			return NULL;
		}
		if (list.size() == 0) {
			return EMPTY;
		}

		StringBuffer str = new StringBuffer();
		str.append("{");

		Object[] arr = list.toArray();
		for (int i = 0; i < arr.length; i++) {
			str.append(arr[i].toString()).append(',');
		}
		str.replace(str.length() - 2, str.length(), "}");
		return str.toString();
	}

	private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	private static char toHex(int nibble) {
		return hexDigit[(nibble & 0xF)];
	}

	/**
	 * 将字符串编码成 Unicode 。
	 * @param theString   待转换成Unicode编码的字符串。
	 * @param escapeSpace 是否忽略空格。
	 * @return 返回转换后Unicode编码的字符串。
	 */
	public static String toUnicode(String theString, boolean escapeSpace) {
		int len = theString.length();
		int bufLen = len * 2;
		if (bufLen < 0) {
			bufLen = Integer.MAX_VALUE;
		}
		StringBuffer outBuffer = new StringBuffer(bufLen);

		for (int x = 0; x < len; x++) {
			char aChar = theString.charAt(x);
			// Handle common case first, selecting largest block that
			// avoids the specials below
			if ((aChar > 61) && (aChar < 127)) {
				if (aChar == '\\') {
					outBuffer.append('\\');
					outBuffer.append('\\');
					continue;
				}
				outBuffer.append(aChar);
				continue;
			}
			switch (aChar) {
			case ' ':
				if (x == 0 || escapeSpace)
					outBuffer.append('\\');
				outBuffer.append(' ');
				break;
			case '\t':
				outBuffer.append('\\');
				outBuffer.append('t');
				break;
			case '\n':
				outBuffer.append('\\');
				outBuffer.append('n');
				break;
			case '\r':
				outBuffer.append('\\');
				outBuffer.append('r');
				break;
			case '\f':
				outBuffer.append('\\');
				outBuffer.append('f');
				break;
			case '=': // Fall through
			case ':': // Fall through
			case '#': // Fall through
			case '!':
				outBuffer.append('\\');
				outBuffer.append(aChar);
				break;
			default:
				if ((aChar < 0x0020) || (aChar > 0x007e)) {
					outBuffer.append('\\');
					outBuffer.append('u');
					outBuffer.append(toHex((aChar >> 12) & 0xF));
					outBuffer.append(toHex((aChar >> 8) & 0xF));
					outBuffer.append(toHex((aChar >> 4) & 0xF));
					outBuffer.append(toHex(aChar & 0xF));
				} else {
					outBuffer.append(aChar);
				}
			}
		}
		return outBuffer.toString();
	}

	/**
	 * 从 Unicode码转换成编码前的特殊字符串。
	 * @param in   Unicode编码的字符数组。
	 * @param off  转换的起始偏移量。
	 * @param len  转换的字符长度。
	 * @return     完成转换，返回编码前的特殊字符串。
	 */
	public static String fromUnicode(char[] in, int off, int len) {
		int newLen = len * 2;
		if (newLen < 0) {
			newLen = Integer.MAX_VALUE;
		}
		char[] convtBuf = new char[newLen];

		char aChar;
		char[] out = convtBuf;
		int outLen = 0;
		int end = off + len;

		while (off < end) {
			aChar = in[off++];
			if (aChar == '\\') {
				aChar = in[off++];
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = in[off++];
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
						}
					}
					out[outLen++] = (char) value;
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					out[outLen++] = aChar;
				}
			} else {
				out[outLen++] = (char) aChar;
			}
		}
		return new String(out, 0, outLen);
	}

	/**
	 * 
	 */
	public static String format(String str, Object... args) {
		for (int i = 0; i < args.length; i++) {
			String key = "{" + i + '}';
			str = StringUtils.replace(str, key, args[i].toString());
		}
		return str;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(check("D-d_", new char[] { 'a', 'z', 'A', 'Z' }, new char[] { '_' }));
	}

}
